package cn.cosmosx.base.util;

import cn.cosmosx.base.constant.GlobalConstant;
import cn.cosmosx.base.constant.ResultCode;
import cn.cosmosx.base.exception.PlatformException;
import cn.cosmosx.base.helper.SpringContextHolder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * cookie工具类
 * 线上版本禁用cookie,此工具类仅作为配合swagger方便测试使用
 */
public class CookieUtils {

    /**
     * 保存token
     * @param token
     * @param response
     */
    public static void saveToken(String token, HttpServletResponse response) {
        if (!enableSwagger()) {
            return;
        }
        Cookie cookie = new Cookie(GlobalConstant.TOKEN, token);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 清除cookie
     * @param response
     */
    public static void cleanToken(HttpServletResponse response) {
        if (!enableSwagger()) {
            return;
        }
        Cookie cookie = new Cookie(GlobalConstant.TOKEN, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        //重置客户端header中的认证信息
        response.setHeader(GlobalConstant.TOKEN, "");
    }

    /**
     * 获取cookie中的token
     * @param request
     * @return
     */
    public static String getToken(HttpServletRequest request) {
        if (!enableSwagger()) {
            return null;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            throw new PlatformException(ResultCode.E00005);
        }
        Optional<Cookie> cookieOptional = Arrays.stream(cookies)
                .filter(c -> GlobalConstant.TOKEN.equalsIgnoreCase(c.getName()))
                .findFirst();
        return cookieOptional.map(Cookie::getValue).orElseThrow(() -> new PlatformException(ResultCode.E00005));
    }

    static boolean enableSwagger() {
        return SpringContextHolder.getProperty("qs.swagger.enable", Boolean.class);
    }
}
